package com.example.filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        
        // 获取请求的URI
        String uri = req.getRequestURI();
        
        System.out.println("AuthFilter已执行：正在检查URI - " + uri);
        
        // 1. 如果请求的是登录页面或登录处理本身，直接放行
        if (uri.endsWith("login.jsp") || uri.endsWith("/login")) {
            chain.doFilter(request, response);
            return;
        }

        // 2. 如果请求的是/admin/目录下的资源
        if (uri.contains("/admin/")) {
            HttpSession session = req.getSession(false); // false表示不创建新session
            // 检查session是否存在，并且session中是否有"user"属性
            if (session != null && session.getAttribute("user") != null) {
                // 用户已登录，放行
                System.out.println("用户已登录，允许访问管理员页面。");
                chain.doFilter(request, response);
            } else {
                // 用户未登录，重定向到登录页面
                System.out.println("用户未登录，跳转到登录页。");
                res.sendRedirect(req.getContextPath() + "/login.jsp");
            }
        } else {
            // 3. 其他所有公共资源，直接放行
            chain.doFilter(request, response);
        }
    }
    
    // init 和 destroy 方法可以保留为空
    @Override public void init(FilterConfig fConfig) throws ServletException {}
    @Override public void destroy() {}
}